package dbutils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 封装泛型工具类
 * Created by kevin on 2020/4/2.
 */
public class QR<T> {
    private DataSource dataSource;

    public QR() {
        super();
    }

    public QR(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 增删改
     * @param sql
     * @param parms
     * @return
     */
    public int update(String sql,Object...parms){
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = dataSource.getConnection();
            pstmt = connection.prepareStatement(sql);
            initParams(pstmt,parms);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
           throw new RuntimeException(e);
        } finally {
            try {
                if(pstmt!=null){
                    pstmt.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void initParams(PreparedStatement pstmt,Object...parms){
        try {
            for(int i=0;i<parms.length;i++){
                pstmt.setObject(i+1,parms[i]);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询单个对象
     * @param sql
     * @param rh
     * @param parms
     * @return
     */
    public T query(String sql,RsHandler<T> rh,Object...parms){
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            connection = dataSource.getConnection();
            pstmt = connection.prepareStatement(sql);
            initParams(pstmt,parms);
            rs = pstmt.executeQuery();
            return rh.handle(rs);
        } catch (SQLException e) {
           throw new RuntimeException(e);
        } finally {
            try {
                if(pstmt!=null){
                    pstmt.close();
                }
                if(rs!=null){
                    rs.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

/**
 * 处理对象映射
 * @param <T>
 */
interface RsHandler<T>{
    public T handle(ResultSet rs) throws SQLException;
}
